package com.ipay.controller;

import java.io.PrintWriter;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.util.TextUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.ipay.entity.TradeRecord;
import com.ipay.service.CashiersService;
import com.ipay.service.TradeRecordService;
import com.ipay.utils.Constant;
import com.ipay.utils.StringUtil;

/***
 *
 *
 * 交易管理的业务处理
 *
 * @data 2017.08.31
 * @author shi.wu
 *
 */
@Controller
public class TradingController {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private TradeRecordService tradeRecordService;
    @Autowired
    private CashiersService cashiersService;

	@RequestMapping("trading/{url}.html")
	public String page(@PathVariable("url") String url) {
		return "trading/" + url + ".html";
	}

    /**
     * 跳转到交易中心
     *
     * @param request
     * @return
     */
    @RequestMapping("/trading/center")
    public ModelAndView isApply(HttpServletRequest request, ModelMap map) {
        String busId = (String) request.getSession().getAttribute("busId");
        busId="D2017091910000000008";
        String resource = (String) request.getParameter("resource");//来源
        String status = (String) request.getParameter("status");//支付状态
        String orderdateBegin = (String) request.getParameter("orderdateBegin");//开始时间
        String orderdateEnd = (String) request.getParameter("orderdateEnd");//结束时间
        logger.info("===========resource:" + resource+"===========status:" + status+"===========orderdateBegin:" + orderdateBegin+"===========orderdateEnd:" + orderdateEnd);
        // 根据openid查询商户订单时间分组数据
        TradeRecord payorder=new TradeRecord();
        if(StringUtil.isNotEmpty(resource)){
            String[] resourceSz=resource.split(",");
            List<String> list = Arrays.asList(resourceSz);
            payorder.setResourceList(list);
        }
        if(StringUtil.isNotEmpty(status)){
            String[] statusSz=status.split(",");
            List<String> list = Arrays.asList(statusSz);
            payorder.setStatusList(list);
        }

        if(StringUtil.isNotEmpty(orderdateBegin)){payorder.setOrderdateBegin(orderdateBegin+" 00:00:01");}
        if(StringUtil.isNotEmpty(orderdateEnd)){payorder.setOrderdateEnd(orderdateEnd+" 23:59:59");}

        //查询当前用户信息（主要判断是1商户还是2收款员）
        Map<String, Object> mapDatetrade = new HashMap<>();
        payorder.setBusId(busId);
        mapDatetrade.put("busId", busId);
        List<Map<String, Object>> dateGroupingList = tradeRecordService.findDateGrouping(payorder);
        // 查询商户订单信息
        List<TradeRecord> tradeRecordList = tradeRecordService.findTradeRecordPage(payorder);
        // /今日交易金额
        BigDecimal todaySumAmount = tradeRecordService
                .findTodaySumAmount(mapDatetrade);
        if (todaySumAmount == null) {
            todaySumAmount = BigDecimal.valueOf(0);
        }
        // /成功交易笔数
        Integer countRecord = tradeRecordService.findCountRecord(mapDatetrade);
        if (countRecord == null) {
            countRecord = 0;
        }

        SimpleDateFormat df = new SimpleDateFormat("MM-dd");
        String today = df.format(new Date());
        map.put("today", today); // 系统当前时间
        map.put("dateGroupingList", dateGroupingList); // 日期分组
        map.put("tradeRecordList", tradeRecordList); // 商户所有收款信息
        map.put("todaySumAmount", todaySumAmount); // 今日交易金额
        map.put("countRecord", countRecord); // 成功交易笔数
        map.put("payorder", payorder); //页面传入参数
        map.put("resource", resource); ////来源
        map.put("status", status); ////支付状态
        map.put("orderdateBegin", orderdateBegin); //开始时间
        map.put("orderdateEnd", orderdateEnd); //结束时间
        return new ModelAndView("tradingcenter.jsp");

    }

    /**
     * 订单详情
     *
     * @param recordNo 订单编号
     * @param request
     * @param map
     * @return
     */
    @RequestMapping("/trading/details")
    public ModelAndView details(@RequestParam String recordNo,
                                HttpServletRequest request, ModelMap map) {
        /*String openid = (String) request.getSession().getAttribute("openid");*/
        TradeRecord dateGroupingTk = tradeRecordService.findTradeRecordDetails(recordNo);
        map.put("dateGroupingTk", dateGroupingTk);
        if (dateGroupingTk != null) {
            if (StringUtil.isNotEmpty(dateGroupingTk.getCategory()) && Constant.CATEGORY_ZF.equals(dateGroupingTk.getCategory())) { //支付进入
                ///查询订单是否申请的退款
                boolean bool=false;
                if (StringUtil.isNotEmpty(dateGroupingTk.getRecordNo())) {
                    //查询下已退款金额
                    Map<String, Object> mapTradeRec = new HashMap<>();
                    mapTradeRec.put("orderId", dateGroupingTk.getRecordNo());
                    BigDecimal refundSumAmount = tradeRecordService.findRefundSumAmount(mapTradeRec);
                    if(refundSumAmount==null){
                        refundSumAmount=BigDecimal.valueOf(0);
                    }
                    map.put("refundSumAmount", refundSumAmount);
                    if (refundSumAmount.compareTo(dateGroupingTk.getAmount()) == -1) { //结果是:-1 小于,0 等于,1 大于
                        bool = true;
                    }
                }
                map.put("tkButtonShow", bool);

                return new ModelAndView("tradingDetails.jsp");
            } else { //(dateGroupingTk!=null&&dateGroupingTk.getCategory().intValue()==1)
                TradeRecord dateGrouping = tradeRecordService
                        .findTradeRecordDetails(dateGroupingTk.getOrderId());
                map.put("dateGrouping", dateGrouping);
                return new ModelAndView("showRefund.jsp");
            }
        } else {
            return new ModelAndView("/trading/center");
        }
    }
}
